package com.newtouch.bxzs.business.train.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Objects;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.newtouch.bxzs.business.train.mapper.ExaminationQuestionMapper;
import com.newtouch.bxzs.business.train.mapper.QuestionBankMapper;
import com.newtouch.bxzs.business.train.model.bo.ExaminationQuestionSetQuestionBankListBO;
import com.newtouch.bxzs.business.train.model.bo.QuestionBankListBO;
import com.newtouch.bxzs.business.train.model.vo.ExaminationQuestionSetQuestionBankListVO;
import com.newtouch.bxzs.business.train.model.vo.ModifyQuestionBankInfoVO;
import com.newtouch.bxzs.business.train.model.vo.QuestionBankListVO;
import com.newtouch.bxzs.business.train.service.QuestionBankService;
import com.newtouch.bxzs.common.base.BaseException;
import com.newtouch.bxzs.common.base.model.ExaminationQuestion;
import com.newtouch.bxzs.common.base.model.QuestionBank;
import com.newtouch.bxzs.common.base.model.bo.PageParam;
import com.newtouch.bxzs.common.base.util.UserDetailUtil;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;

/**
 * 题库管理
 *
 * <p>
 * <b>History:</b>
 * <table border="1">
 * <tr>
 * <th>Date</th>
 * <th>Operator</th>
 * <th>Memo</th>
 * </tr>
 * <tr>
 * <td>2021年2月5日</td>
 * <td>dongjinlin</td>
 * <td>Create</td>
 * </tr>
 * </table>
 * 
 * @author dongjinlin
 * 
 * @version TODO
 * @since
 */
@Service
public class QuestionBankServiceImpl implements QuestionBankService {

	/** 静态变量：系统日志 */
	private static final Log logger = LogFactory.getLog(QuestionBankService.class);

	@Autowired
	private QuestionBankMapper questionBankMapper;

	@Autowired
	private ExaminationQuestionMapper examinationQuestionMapper;

	/**
	 * 获取题库列表
	 * 
	 * @param QuestionBankListVO
	 * @return
	 */
	@Override
	public IPage<QuestionBankListBO> getQuestionBankList(QuestionBankListVO questionBankListVO) {
		/* 校验 */
		if (checkListPageParam(questionBankListVO)) {
			logger.info("查询列表失败");
			throw new BaseException("-1", "传入数据有误");
		}
		String questionBankName = questionBankListVO.getQuestionBankName();
		Page<QuestionBankListBO> page = new Page<>(questionBankListVO.getCurrentPage(), questionBankListVO.getPageSize());
		return questionBankMapper.getQuestionBankList(questionBankName, page);
	}

	/**
	 * 新增或修改题库信息
	 * 
	 * @param modifyQuestionBankInfoVO
	 * @return
	 */
    @Override
    public String modifyQuestionBankInfo(ModifyQuestionBankInfoVO modifyQuestionBankInfoVO) {

        /* 判断传入数据是否合格 */
        if (modifyQuestionBankInfoVO == null) {
            logger.info("新增或修改失败");
            throw new BaseException("-1", "传入数据有误");
        }
        /* 校验必传参数 */
        if (StringUtils.isEmpty(modifyQuestionBankInfoVO.getQuestionBankName())
            || null == modifyQuestionBankInfoVO.getQuestionBankType()
            || null == modifyQuestionBankInfoVO.getQuestionBankDescription()) {
            logger.info("新增或修改失败");
            throw new BaseException("-1", "有必填项未填！");
        }

        QuestionBank questionBank = new QuestionBank();
        /* 使用工具直接进行实体与BO的复制转换，注意字段名及类型需保持一致 */
        BeanUtil.copyProperties(modifyQuestionBankInfoVO, questionBank);

        if (null == modifyQuestionBankInfoVO.getQuestionBankId()
            || "".equals(modifyQuestionBankInfoVO.getQuestionBankId())) {
            /* 新增试卷 */
            logger.info("新增题库基本信息");
            questionBank.setCreateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId());
            questionBank.setCreateTime(new Date());
            questionBank.setUpdateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail().getUserId()));
            questionBank.setUpdateTime(new Date());
            questionBank.setIsDelete(false);

            questionBankMapper.insert(questionBank);

            if (modifyQuestionBankInfoVO.getExaminationQuestionList() != null
                && (modifyQuestionBankInfoVO.getExaminationQuestionList().size() > 0)) {
                updateExaminationQuestionSetQuestionBankId(questionBank.getQuestionBankId(),
                    modifyQuestionBankInfoVO.getExaminationQuestionList());
            }
        } else {
            /* 修改 */
            logger.info("修改题库基本信息");
            questionBank.setUpdateUserId(
                Objects.requireNonNull(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId()));
            questionBank.setUpdateTime(new Date());
            questionBankMapper.updateById(questionBank);

            if (modifyQuestionBankInfoVO.getExaminationQuestionList() != null
                && (modifyQuestionBankInfoVO.getExaminationQuestionList().size() > 0)) {
                updateExaminationQuestionSetQuestionBankId(questionBank.getQuestionBankId(),
                    modifyQuestionBankInfoVO.getExaminationQuestionList());
            }
        }
        return questionBank.getQuestionBankId();
    }

	/**
	 * 删除题库
	 * 
	 * @param questionBankIds
	 */
	@Override
	public Integer deleteQuestionBank(List<String> questionBankIds) {
		/* 校验 */
		if (CollectionUtil.isEmpty(questionBankIds)) {
			logger.info("删除失败");
			throw new BaseException("-1", "集合为空");
		}
		/* 批量逻辑删除产品 */
		int affrectRows=questionBankMapper.deleteBatchIds(questionBankIds);
		logger.info("删除成功"+affrectRows+"条");
		return affrectRows;
	}

	/**
	 * 更新众多试题的题库id
	 */
	public void updateExaminationQuestionSetQuestionBankId(String questionBankId, List<String> examinationQuestionIds) {
		if (questionBankId == null || examinationQuestionIds == null || examinationQuestionIds.size() <= 0) {
			throw new BaseException("-1", "传入数据有误");
		}

		ExaminationQuestion examinationQuestion = new ExaminationQuestion();

		examinationQuestion.setQuestionBankId(questionBankId);
		examinationQuestion.setUpdateTime(new Date());
		examinationQuestion.setUpdateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail().getUserId()));
		examinationQuestion.setIsDelete(false);
		UpdateWrapper<ExaminationQuestion> updateWrapper = new UpdateWrapper<>();
		updateWrapper.in("EXAMINATION_QUESTIONS_ID", examinationQuestionIds);

		int affectRows = examinationQuestionMapper.update(examinationQuestion, updateWrapper);
		logger.info("修改了" + affectRows);
	}

	/**
	 * 校验分页参数
	 * 
	 * @param pageParam
	 * @return
	 */
	private boolean checkListPageParam(PageParam pageParam) {
		if (pageParam == null || pageParam.getPageSize() == null || pageParam.getCurrentPage() == null
				|| StringUtils.isEmpty(pageParam.getPageSize()) || StringUtils.isEmpty(pageParam.getCurrentPage())
				|| pageParam.getCurrentPage() < 1) {
			return true;
		}
		return false;
	}

    /* 
     * 试题设置题库列表
     */
    @Override
    public IPage<ExaminationQuestionSetQuestionBankListBO> getExaminationQuestionSetQuestionBankList(
        ExaminationQuestionSetQuestionBankListVO examinationQuestionSetQuestionBankListVO) {
        if (checkListPageParam(examinationQuestionSetQuestionBankListVO)) {
            logger.info("查询列表失败");
            throw new BaseException("-1", "传入数据有误");
        }
        String examinationQuestionId = examinationQuestionSetQuestionBankListVO.getExaminationQuestionId();
        Page<ExaminationQuestionSetQuestionBankListBO> page = new Page<>(examinationQuestionSetQuestionBankListVO.getCurrentPage(),examinationQuestionSetQuestionBankListVO.getPageSize());
        return questionBankMapper.getExaminationQuestionSetQuestionBankList(examinationQuestionId, page);
    }
}
